var socket;
var errorCount = 0;
var isConnected = false;
var maxError = 5;
var isJoin = false;
var socketId = '';
// connect(null,null);
var nickName = parseInt(Math.random() * 10000);
var nickName = 123456;
var roomId = '';
var game_ting = [];
var game_gang=[];

$('#nickName').val(nickName);
function connect(url, clientId) {
  if (url == '' || url == null || url == undefined) {
    url = 'http://localhost:8080';
  }
  nickName = $('#nickName').val();
  // socket = io.connect(url, opts);
  var query = 'nickName=' + nickName + '&userId=' + nickName;
  socket = io(url + '?' + query, { transports: ['websocket'] });

  socket.on('connected', function (data) {
    isConnected = true;
    console.log('连接成功', data);
    socketId = data.id;
    serverOutput(
      '<span class="connect-msg"><font color="blue">' +
        getNowTime() +
        '&nbsp;</font>' +
        data.message +
        '</span>',
    );
    //链接成功 自动加入

    errorCount = 0;
  });
  socket.on('message', function (data) {
    if (data.type == 'message') {
      output(
        '<span class="userName-msg"><font color="blue">' +
          getNowTime() +
          '&nbsp;</font>用户' +
          data.nickName +
          '：' +
          data.message +
          ' </span>',
      );
      console.log(data);
    } else if (data.type == 'systemMessage') {
      output(
        '<span class="userName-msg"><font color="blue">' +
          getNowTime() +
          '&nbsp;</font>用户' +
          data.userId +
          '：' +
          data.message +
          ' </span>',
      );
      console.log(data);
    } else {
      serverOutput(
        '<span class="disconnect-msg"><font color="blue">' +
          getNowTime() +
          '&nbsp;</font>用户' +
          data.userId +
          '：还不是好友 </span>',
      );
    }
  });

  socket.on('messageGroup', function (data) {
    output(
      '<span class="userName-msg"><font color="blue">' +
        getNowTime() +
        '&nbsp;</font>群消息' +
        data.nickName +
        '：' +
        data.message +
        ' </span>',
    );
    console.log(data);
  });

  socket.on('joinAgreeGroup', function (data) {
    if (data.toAdmin == 'invited') {
      if (data.type == 'agree') {
        serverOutput(
          '<span class="connect-msg"><font color="blue">' +
            getNowTime() +
            '&nbsp;</font>' +
            data.userId +
            '同意进群了 </span>',
        );
        isJoin = true;
        joinRoom(data).then((res) => {});
      } else {
        serverOutput(
          '<span class="connect-msg"><font color="blue">' +
            getNowTime() +
            '&nbsp;</font>' +
            data.userId +
            '不同意进群 </span>',
        );
      }
    } else {
      if (data.type == 'agree') {
        isJoin = true;
        serverOutput(
          '<span class="connect-msg"><font color="blue">' +
            getNowTime() +
            '&nbsp;</font> 同意进群了 </span>',
        );
        joinRoom(data).then((res) => {});
      } else {
        serverOutput(
          '<span class="disconnect-msg"><font color="blue">' +
            getNowTime() +
            '&nbsp;</font>' +
            data.roomId +
            ' 的群主' +
            data.ownerId +
            '拒绝了您进群 </span>',
        );
      }
    }
  });

  socket.on('joinGroup', function (data) {
    if (data.roomId) {
      if (data.userId == nickName) {
        isJoin = true;
        joinRoom(data).then((res) => {});
      }
      if (data.message) {
        output(
          '<span class="userName-msg"><font color="blue">' +
            getNowTime() +
            '&nbsp;</font>' +
            data.userId +
            ',' +
            data.message +
            '</span>',
        );
        console.log(data);
      } else {
        output(
          '<span class="userName-msg"><font color="blue">' +
            getNowTime() +
            '&nbsp;</font>' +
            data.userId +
            '加入房间</span>',
        );
        console.log(data);
      }
    } else {
      output(
        '<span class="disconnect-msg"><font color="blue">' +
          getNowTime() +
          '&nbsp;</font>' +
          data.message +
          '</span>',
      );
      console.log(data);
    }
  });

  socket.on('exitGroup', function (data) {
    if (data.roomId) {
      if (data.ownerId == nickName) {
        isJoin = false;
        output(
          '<span class="userName-msg"><font color="blue">' +
            getNowTime() +
            '&nbsp;</font>' +
            data.ownerId +
            ',' +
            data.message +
            '</span>',
        );
        console.log(data);
      } else {
        output(
          '<span class="userName-msg"><font color="blue">' +
            getNowTime() +
            '&nbsp;</font>' +
            data.ownerId +
            ',退出群聊 </span>',
        );
      }
    }
  });

  socket.on('disconnect', function () {
    if (isConnected) {
      isConnected = false;
      isJoin = false;
      console.log('连接断开');
      socket.close();
      serverOutput(
        '<span class="disconnect-msg"><font color="blue">' +
          getNowTime() +
          '&nbsp;</font>' +
          '已下线! </span>',
      );
      errorCount++;
      if (errorCount <= 100) {
        setTimeout(() => {
          var url = $('#url').val();
          var clientId = $('#clientId').val();
          connect(url, clientId);
        }, 1000);
      }
    }
  });
  socket.on('connect_error', function (data) {
    serverOutput(
      '<span class="disconnect-msg"><font color="blue">' +
        getNowTime() +
        '&nbsp;</font>;' +
        '连接错误-' +
        data +
        ' </span>',
    );
  });
  socket.on('connect_timeout', function (data) {
    serverOutput(
      '<span class="disconnect-msg"><font color="blue">' +
        getNowTime() +
        '&nbsp;</font>' +
        '连接超时-' +
        data +
        ' </span>',
    );
    errorCount++;
    if (errorCount <= maxError) {
      setTimeout(() => {
        var url = $('#url').val();
        var clientId = $('#clientId').val();
        connect(url, clientId);
      }, 1000);
    }
  });
  socket.on('error', function (data) {
    serverOutput(
      '<span class="disconnect-msg"><font color="blue">' +
        getNowTime() +
        '&nbsp;</font>' +
        '系统错误-' +
        data +
        ' </span>',
    );
    errorCount++;
    if (errorCount <= maxError) {
      setTimeout(() => {
        var url = $('#url').val();
        var clientId = $('#clientId').val();
        connect(url, clientId);
      }, 1000);
    }
  });
  socket.on('joinInvitedGroup', function (data) {
    // 群管理的消息
    var text = '用户' + data.userId + '申请加入' + data.roomId + '房间';
    if (data.type == 'invited') {
      text = '群主' + data.ownerId + '邀请您加入' + data.roomId + '房间';
    }
    $('.dialogContent p').text(text);
    show();
    $('#confirm').click(function () {
      hide();
      $('#confirm').unbind();
      socket.emit('joinAgreeGroup', {
        nickName: nickName,
        userId: data.userId,
        roomId: data.roomId,
        ownerId: data.ownerId,
        type: 'agree',
        toAdmin: data.type,
        socketId: socketId,
        message: content,
      });
      if (data.type !== 'invited') {
        serverOutput(
          '<span class="connect-msg"><font color="blue">' +
            getNowTime() +
            '&nbsp;</font>' +
            '同意-' +
            data.userId +
            '进群了 </span>',
        );
      } else {
        $('#clientId').val(data.roomId);
      }
    });
    $('#cancel').click(function () {
      hide();
      $('#cancel').unbind();
      socket.emit('joinAgreeGroup', {
        nickName: nickName,
        userId: data.userId,
        roomId: data.roomId,
        type: 'noagree',
        toAdmin: data.type,
        ownerId: data.ownerId,
        socketId: socketId,
        message: content,
      });
      if (data.type !== 'invited') {
        serverOutput(
          '<span class="disconnect-msg"><font color="blue">' +
            getNowTime() +
            '&nbsp;</font>' +
            '拒绝-' +
            data.userId +
            '进群了 </span>',
        );
      }
    });
  });

  socket.on('ack', function (data) {
    var str = '消息发送失败';
    if (data == 1) {
      str = '消息发送成功';
    }
    serverOutput(
      '<span class="connect-msg"><font color="blue">' +
        getNowTime() +
        '&nbsp;</font>' +
        str +
        ' </span>',
    );
  });

  socket.on(resp.game_holds, function (data) {
    if (data.type == resp.game_holds) {
      var pais = data.message;
      holds = pais.holds;
      output(
        '<span class="disconnect-msg"><font color="blue">' +
          getNowTime() +
          '&nbsp;</font>----------------摸牌：' +
          getName(holds) +
          ' </span>',
      );
      output(
        '<span class="username-msg"><font color="blue">' +
          getNowTime() +
          '&nbsp;</font>----------------理牌：' +
          getName(sort(holds)) +
          ' </span>',
      );
      $('#paidata').text( getName(sort(holds)))

      console.log(data);
    } else {
      serverOutput(
        '<span class="disconnect-msg"><font color="blue">' +
          getNowTime() +
          '&nbsp;</font>' +
          '已下线! </span>',
      );
    }
  });

  socket.on(resp.mj_count, function (data) {
    if (data.type == resp.mj_count) {
      var data = data.message;
      output(
        '<span class="username-msg"><font color="blue">' +
          getNowTime() +
          '&nbsp;</font>剩余张数：' +
          data +
          ' </span>',
      );
      $('#mj_count').text(data);
      console.log(data);
    } else {
      serverOutput(
        '<span class="disconnect-msg"><font color="blue">' +
          getNowTime() +
          '&nbsp;</font>' +
          '已下线! </span>',
      );
    }
  });
  socket.on(resp.game_chupai, function (data) {
    if (data.type == resp.game_chupai) {
      chupaiUserId = data.message;
      output(
        '<span class="username-msg"><font color="blue">' +
          getNowTime() +
          '&nbsp;</font>轮到：' +
          chupaiUserId +
          ' 出牌</span>',
      );
      console.log(data);
    } else {
      serverOutput(
        '<span class="disconnect-msg"><font color="blue">' +
          getNowTime() +
          '&nbsp;</font>' +
          '已下线! </span>',
      );
    }
  });
  socket.on(resp.game_ting, function (data) {
    if (data.type == resp.game_ting) {
      game_ting = data.message.tingMap;
      for (let index = 0; index < game_ting.length; index++) {
        const element = game_ting[index];
        output(
          '<span class="username-msg"><font color="blue">' +
            getNowTime() +
            '&nbsp;</font>听牌：' +
            getName(element[1]) +
            ' </span>',
        );
      }
      console.log(game_ting);
    } else {
      serverOutput(
        '<span class="disconnect-msg"><font color="blue">' +
          getNowTime() +
          '&nbsp;</font>' +
          '已下线! </span>',
      );
    }
  });
  socket.on(resp.game_hupai, function (data) {
    if (data.type == resp.game_hupai) {
      game_hu = data.message;
      if (game_hu.type == 'hu') {
        output(
          '<span class="username-msg"><font color="blue">' +
            getNowTime() +
            '&nbsp;</font>' +
            game_hu.userId +
            '糊了：' +
            getName([game_hu.hupai]) +
            ' </span>',
        );
        console.log(data);
      } else if (game_hu.type == 'zimo') {
        output(
          '<span class="username-msg"><font color="blue">' +
            getNowTime() +
            '&nbsp;</font>' +
            game_hu.userId +
            '自摸</span>',
        );
        console.log(data);
      } else if (game_hu.type == 'peng') {
        output(
          '<span class="username-msg"><font color="blue">' +
            getNowTime() +
            '&nbsp;</font>' +
            game_hu.userId +
            '碰了：' +
            getName([game_hu.hupai]) +
            ' </span>',
        );
        console.log(data);
      } else if (game_hu.type == 'gang') {
        output(
          '<span class="username-msg"><font color="blue">' +
            getNowTime() +
            '&nbsp;</font>' +
            game_hu.userId +
            '杠了：' +
            getName([game_hu.hupai]) +
            ' </span>',
        );
        console.log(data);
      }
    } else {
      serverOutput(
        '<span class="disconnect-msg"><font color="blue">' +
          getNowTime() +
          '&nbsp;</font>' +
          '已下线! </span>',
      );
    }
  });

  socket.on(resp.game_mopai, function (data) {
    holds.push(data.message.pai);
    output(
      '<span class="disconnect-msg"><font color="blue">' +
        getNowTime() +
        '&nbsp;</font>摸了：' +
        getName([data.message.pai]) +
        ' </span>',
    );
    output(
      '<span class="username-msg"><font color="blue">' +
        getNowTime() +
        '&nbsp;</font>----------------理牌：' +
        getName(sort(holds)) +
        ' </span>',
    );
  });
  socket.on(resp.game_action, function (data) {
    if (data.type == resp.game_action) {
      game_action = data.message;
      $('input[type=radio][id=action]').eq(4).removeAttr('disabled');

      if (game_action.hu) {
        //可以糊
        $('input[type=radio][id=action]').eq(5).removeAttr('disabled');
      } else if (game_action.peng) {
        //可以碰
        $('input[type=radio][id=action]').eq(0).removeAttr('disabled');
       } else if (game_action.gang) {
        //可以杠
        game_gang =game_action.gangpai
        $('input[type=radio][id=action]').eq(2).removeAttr('disabled');
        if( game_ting.length>0){
          $('input[type=radio][id=action]').eq(1).removeAttr('disabled');
        }
        for (let index = 0; index < game_gang.length; index++) {
          const element =game_gang[index];
          $('#chidata').append(getName([element])+",")

        }
      } else if (game_action.chi) {
        $('input[type=radio][id=action]').eq(3).removeAttr('disabled');
        for (let index = 0; index < game_action.pai.length; index++) {
          const element = game_action.pais[index];
          $('#chidata').append(getName(element)+",")

        }
      }
    } else {
      serverOutput(
        '<span class="disconnect-msg"><font color="blue">' +
          getNowTime() +
          '&nbsp;</font>' +
          '已下线! </span>',
      );
    }
  });
  socket.on(resp.game_chupai_notify, function (data) {
    if (data.type == resp.game_chupai_notify) {
      var msg = data.message;
      console.log("chupai_notify:",data);

      if (msg.userId == data.userId) {
        // 更新自己位置的麻将
        console.log('holds', holds);
        for (let index = 0; index < holds.length; index++) {
          const item = holds[index];
          if (Number(item) == Number(msg.pai)) {
            holds.splice(index, 1);
            break;
          }
        }

        output(
          '<span class="username-msg"><font color="blue">' +
            getNowTime() +
            '&nbsp;</font>>----------------理牌：' +
            getName(sort(holds)) +
            ' </span>',
        );
      } else {
        output(
          '<span class="disconnect-msg"><font color="blue">' +
            getNowTime() +
            '&nbsp;</font>' +
            msg.userId +
            '打出：' +
            getName([msg.pai]) +
            ' 牌</span>',
        );
      }
    } else {
      serverOutput(
        '<span class="disconnect-msg"><font color="blue">' +
          getNowTime() +
          '&nbsp;</font>' +
          '已下线! </span>',
      );
    }
  });
  socket.on(resp.peng_notify, function (data) {
    if (data.type == resp.peng_notify) {
      var msg = data.message;
      console.log(data);

      if (msg.userId == data.userId) {
        // 更新自己位置的麻将
        console.log('holds', holds);
        for (let index = 0; index < holds.length; index++) {
          const item = holds[index];
          if (Number(item) == Number(msg.pai)) {
            holds.splice(index, 1);
            index--;
          }
        }

        output(
          '<span class="username-msg"><font color="blue">' +
            getNowTime() +
            '&nbsp;</font>>----------------碰后牌：' +
            getName(sort(holds)) +
            ' </span>',
        );
      } else {
        // 更新对应位置的麻将
        output(
          '<span class="disconnect-msg"><font color="blue">' +
            getNowTime() +
            '&nbsp;</font>' +
            msg.userId +
            '碰了:' +
            getName([msg.pai]) +
            ' 牌</span>',
        );
      }
    } else {
      serverOutput(
        '<span class="disconnect-msg"><font color="blue">' +
          getNowTime() +
          '&nbsp;</font>' +
          '已下线! </span>',
      );
    }
  });
  socket.on(resp.gang_notify, function (data) {
    if (data.type == resp.gang_notify) {
      var msg = data.message;
      console.log(data);

      if (msg.userId == data.userId) {
        // 更新自己位置的麻将
        console.log('holds', holds);
        for (let index = 0; index < holds.length; index++) {
          const item = holds[index];
          if (Number(item) == Number(msg.pai)) {
            holds.splice(index, 1);
            index--;
          }
        }

        output(
          '<span class="username-msg"><font color="blue">' +
            getNowTime() +
            '&nbsp;</font>>----------------杠后牌：' +
            getName(sort(holds)) +
            ' </span>',
        );
      } else {
        // 更新对应位置的麻将
        output(
          '<span class="disconnect-msg"><font color="blue">' +
            getNowTime() +
            '&nbsp;</font>' +
            msg.userId +
            '杠了:' +
            getName([msg.pai]) +
            ' 牌</span>',
        );
      }
    } else {
      serverOutput(
        '<span class="disconnect-msg"><font color="blue">' +
          getNowTime() +
          '&nbsp;</font>' +
          '已下线! </span>',
      );
    }
  });
  socket.on(resp.chi_notify, function (data) {
    if (data.type == resp.chi_notify) {
      var msg = data.message;
      console.log(data);

      if (msg.userId == data.userId) {
        // 更新自己位置的麻将
        var index = -1;
        console.log('item', msg.pais);

        console.log('holds', holds);
        msg.pais.map((pai, i) => {
          for (let index = 0; index < holds.length; index++) {
            const item = holds[index];
            if (Number(item) == Number(pai)) {
              holds.splice(index, 1);
              break;
            }
          }
        });

        output(
          '<span class="username-msg"><font color="blue">' +
            getNowTime() +
            '&nbsp;</font>>----------------吃后牌：' +
            getName(sort(holds)) +
            ' </span>',
        );
      } else {
        // 更新对应位置的麻将
        output(
          '<span class="disconnect-msg"><font color="blue">' +
            getNowTime() +
            '&nbsp;</font>' +
            msg.userId +
            '吃了:' +
            getName(msg.pais) +
            ' 牌</span>',
        );
      }
    } else {
      serverOutput(
        '<span class="disconnect-msg"><font color="blue">' +
          getNowTime() +
          '&nbsp;</font>' +
          '已下线! </span>',
      );
    }
  });
}

function getNowTime() {
  var date = new Date();
  var year = date.getFullYear(); //获取当前年份
  var mon = date.getMonth() + 1; //获取当前月份
  var da = date.getDate(); //获取当前日
  var h = date.getHours(); //获取小时
  var m = date.getMinutes(); //获取分钟
  var s = date.getSeconds(); //获取秒
  var ms = date.getMilliseconds();
  var d = document.getElementById('Date');
  var date =
    year + '/' + mon + '/' + da + ' ' + h + ':' + m + ':' + s + ':' + ms;
  return date;
}

function hide() {
  $('.dialog').hide();
  $('.mask').hide();
}
function show() {
  $('.dialog').show();
  $('.mask').show();
}

function createhide() {
  $('.dialog2').hide();
  $('.mask').hide();
}
function createshow() {
  $('.dialog2').show();
  $('.mask').show();
}

$('input[type=radio][name=类型]').change(function () {
  console.log('this.value', this.value);
  if (this.value == '1') {
    $('.model1').show();
    $('.model2').hide();
  } else if (this.value == '2') {
    $('.model1').hide();
    $('.model2').show();
  }
});
